﻿using System;
using System.Windows.Forms;
using System.Diagnostics;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Threading;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media.Animation;
using System.Windows.Controls;

namespace ImaginationFactory
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// 初始化
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();

            // 设置窗口大小及位置，使其占满整个用户区域
            this.Width = System.Windows.SystemParameters.WorkArea.Width;
            this.Height = System.Windows.SystemParameters.WorkArea.Height;
            this.Left = 0;
            this.Top = 0;

            ///
            /// 背景特效
            /// 
            ///
            DoubleAnimationUsingKeyFrames animaOpacity = new DoubleAnimationUsingKeyFrames();
            animaOpacity.KeyFrames.Add(new LinearDoubleKeyFrame(0, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0.2))));
            animaOpacity.KeyFrames.Add(new LinearDoubleKeyFrame(1, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0.5))));
            //animaOpacity.KeyFrames.Add( new LinearDoubleKeyFrame( 0.5, KeyTime.FromTimeSpan( TimeSpan.FromSeconds( 7 ) ) ) );
            //animaOpacity.KeyFrames.Add( new LinearDoubleKeyFrame( 1, KeyTime.FromTimeSpan( TimeSpan.FromSeconds( 8 ) ) ) );

            this.BeginAnimation(Window.OpacityProperty, animaOpacity);

            ///
            /// 启动新线程打开文件对话框
            /// 
            ///
            //Thread thread = new Thread(OpenFileThread);
            //thread.Start();
            MyOpenFileDialog();
        }

        #region 对话框

        /// <summary>
        /// 线程函数
        /// </summary>
        private void OpenFileThread()
        {
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate() { MyOpenFileDialog(); });
        }

        /// <summary>
        /// 打开对话框，选择图片，并设置为VisualBrush中的Image的Source
        /// </summary>
        private void MyOpenFileDialog()
        {
            imageLibrary.MyOpenFileDialog();

            image.Source = imageLibrary.LoadedImage.Source;

            //System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog();
            //dialog.Title = "Load an image...";
            //dialog.Multiselect = false;

            //if ( dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK )
            //{
            //    string picUri = dialog.FileName;
            //    BitmapImage bitmap = new BitmapImage();
            //    bitmap.BeginInit();
            //    bitmap.UriSource = new Uri( picUri );
            //    bitmap.EndInit();

            //    image.Source = bitmap;
            //}

            UpdateInfoTextBlock();
        }
        

        #endregion

        #region 鼠标操作

        private bool m_IsMouseLeftButtonDown;
        private Stopwatch sw = new Stopwatch();

        /// <summary>
        /// 左键弹起，释放控制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MasterImage_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            ContentControl rectangle = sender as ContentControl;

            if (rectangle == null)
            {
                return;
            }

            m_IsMouseLeftButtonDown = false;

        }


        private Point m_PreviousMousePoint;     /// 记录鼠标的坐标

        /// <summary>
        /// 鼠标左键按下
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MasterImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            
            ContentControl rectangle = sender as ContentControl;

            if (rectangle == null)
            {
                return;
            }

            rectangle.CaptureMouse();
            m_IsMouseLeftButtonDown = true;
            m_PreviousMousePoint = e.GetPosition(rectangle);

            // 计时器开始
            //sw.Reset();
            //startPoint = e.GetPosition( MasterImage );
            //sw.Start();
        }

        /// <summary>
        /// 鼠标移动时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MasterImage_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            ContentControl rectangle = sender as ContentControl;
            if (rectangle == null)
            {
                return;
            }

            UpdateInfoTextBlock();

            if (m_IsMouseLeftButtonDown)
            {
                DoImageMove(rectangle, e);

                /// 每100毫秒取一次点
                //if ( sw.IsRunning && sw.ElapsedMilliseconds > 50 )
                //{
                //    sw.Reset();
                //    startPoint = e.GetPosition( MasterImage );
                //    sw.Start();
                //}
            }
        }

        Point startPoint;
        /// <summary>
        /// 移动图片
        /// </summary>
        /// <param name="rectangle"></param>
        /// <param name="e"></param>
        private void DoImageMove(ContentControl rectangle, System.Windows.Input.MouseEventArgs e)
        {
            if (e.LeftButton != MouseButtonState.Pressed)
            {
                return;
            }

            TransformGroup group = MainPanel.FindResource("ImageTransformResource") as TransformGroup;
            Debug.Assert(group != null);
            TranslateTransform transform = group.Children[1] as TranslateTransform;

            Point position = e.GetPosition(rectangle);
            transform.X += position.X - m_PreviousMousePoint.X;
            transform.Y += position.Y - m_PreviousMousePoint.Y;

            m_PreviousMousePoint = position;
        }

        /// <summary>
        /// 鼠标中键滚动缩放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MasterImage_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            TransformGroup group = MainPanel.FindResource("ImageTransformResource") as TransformGroup;
            Debug.Assert(group != null);

            ScaleTransform transform = group.Children[0] as ScaleTransform;
            TranslateTransform offsetTran = group.Children[1] as TranslateTransform;

            Point ptOnImg = Mouse.GetPosition(image);
            double delta = e.Delta * 0.002 * (transform.ScaleX > 1 ? Math.Pow(2 * transform.ScaleX, 1) : Math.Pow(transform.ScaleX, 0.5));

            #region 非动画放缩
            /// 修正位移
            /// 
            offsetTran.X -= ptOnImg.X * delta;
            offsetTran.Y -= ptOnImg.Y * delta;

            /// 进行放缩
            transform.ScaleX += delta;
            transform.ScaleY += delta;

            /// Method 2: Error
            /// 
            //double x = transform.ScaleX, y = transform.ScaleY;
            //transform.ScaleX = 1; transform.ScaleY = 1;
            //if ( delta > 0 )
            //{
            //    transform.CenterX = ptOnImg.X;
            //    transform.CenterY = ptOnImg.Y;
            //}
            //transform.ScaleX = x + delta; transform.ScaleY = y + delta;
            #endregion

            #region 删除的
            //transform.CenterX = image.ActualWidth / 2;
            //transform.CenterY = image.ActualHeight / 2;

            //if ( delta > 0 )
            //{
            //    transform.CenterX = ptOnImg.X;
            //    transform.CenterY = ptOnImg.Y;
            //}

            ///// 渐渐放大的动画
            //DoubleAnimation animation = new DoubleAnimation();

            ///// 放大的倍率根据已经倍率值来进行修正
            ///// 倍率越大每次放大的倍率越大，反之越小。

            //animation.By = delta;
            //animation.AccelerationRatio = 0.5;
            //animation.DecelerationRatio = 0.4;
            //animation.Duration = new Duration( TimeSpan.FromSeconds( 0.2 ) );

            //transform.BeginAnimation( ScaleTransform.ScaleXProperty, animation );
            //transform.BeginAnimation( ScaleTransform.ScaleYProperty, animation );
            #endregion

            UpdateInfoTextBlock();
        }


        #endregion

        #region 辅助函数 ———— 显示信息

        private void UpdateInfoTextBlock()
        {
            TransformGroup group = MainPanel.FindResource("ImageTransformResource") as TransformGroup;
            Debug.Assert(group != null);
            ScaleTransform transform = group.Children[0] as ScaleTransform;
            TranslateTransform offsetTran = group.Children[1] as TranslateTransform;

            Point pt = Mouse.GetPosition(image);
            Point pointToContent = group.Inverse.Transform(pt);
            Point originPoint = offsetTran.Inverse.Transform(pt);

            textBlock.Text = "MasterImage : " + Math.Floor(MasterImage.ActualWidth).ToString() + ' ' + Math.Floor(MasterImage.ActualHeight).ToString()
                + "\niamge: " + Math.Floor(image.ActualWidth).ToString() + ' ' + Math.Floor(image.ActualHeight).ToString()
                //+ "\nInversePt = " + Math.Floor( pointToContent.X ).ToString() + ' ' + Math.Floor( pointToContent.Y ).ToString() 
                + "\noriginPoint = " + Math.Floor(originPoint.X).ToString() + ' ' + Math.Floor(originPoint.Y).ToString()
                + "\n放缩中心：" + Math.Floor(transform.CenterX) + ' ' + Math.Floor(transform.CenterY)
                + "\npt = " + Math.Floor(pt.X).ToString() + ' ' + Math.Floor(pt.Y).ToString() + '\n'
                + "\n放缩: " + Math.Floor(transform.CenterX).ToString() + ' ' + Math.Floor(transform.CenterY).ToString()
                + "\n位移：" + Math.Floor(offsetTran.X) + ' ' + Math.Floor(offsetTran.Y)
                + "\n" + Math.Floor((transform.ScaleX) * 100) + " %\n";
        }

        #endregion

        /// <summary>
        /// 点击关闭程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void MasterImage_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            TransformGroup group = MainPanel.FindResource("ImageTransformResource") as TransformGroup;
            Debug.Assert(group != null);
            ScaleTransform transform = group.Children[0] as ScaleTransform;

            transform.CenterX = 100;
            transform.CenterY = 100;

            transform.ScaleX = 2;
            transform.ScaleY = 2;

            //System.Windows.MessageBox.Show( "Keydown" );
        }



        #region 弹出ListBox

        private void StartButton_Click(object sender, RoutedEventArgs e)
        {

            //Dialogs.MainListBox mlb = new ImaginationFactory.Dialogs.MainListBox();
            //mlb.Show();
            //mlb.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            //mlb.VerticalAlignment = VerticalAlignment.Bottom;
            //mlb.Topmost = true;
        }


        #endregion

        #region 图像处理
        //---------------------------------------------------------------
        // 图像处理库
        //
        private ImageLibrary imageLibrary = new ImageLibrary();
        public ImageLibrary ImageLibrary
        {
            get
            {
                return imageLibrary;
            }
            set
            {
                imageLibrary = value;
            }
        }


        //
        // 将 imageLibrary 中的图像装载并显示出来
        //
        //
        public void ShowPicture()
        {
            //MasterImage.Content = imageLibrary.LoadedImage;
        }
        //
        // 反色
        //
        //
        private void InvertColors_Click(object sender, RoutedEventArgs e)
        {
            imageLibrary.InvertColors();

            MasterImage.Content = imageLibrary.LoadedImage;
        }

        //
        // 水平镜像
        //
        //
        private void HorizonMirror_Click(object sender, RoutedEventArgs e)
        {
            imageLibrary.MirrorEffect(Mirror_Sign.Left_Right);

            MasterImage.Content = imageLibrary.LoadedImage;
        }


        //
        // 上下镜像
        //
        //
        private void verticalMirror_Click(object sender, RoutedEventArgs e)
        {
            imageLibrary.MirrorEffect(Mirror_Sign.On_Down);

            MasterImage.Content = imageLibrary.LoadedImage;
        }



        ////
        //// 裁剪 【 测试 】
        ////
        ////
        //private void CutOutImage(object sender, RoutedEventArgs e)
        //{
        //    imageLibrary.CutOutImage(new Point(500, 300), new Point(1000, 800));

        //    RefreshPhotoViewBoxSize();
        //    photoViewBox.Child = imageLibrary.LoadedImage;
        //}

        ////
        //// 旋转【 测试 】
        ////
        ////
        //private void RotateImage(object sender, RoutedEventArgs e)
        //{
        //    imageLibrary.RotateImage(30);

        //    RefreshPhotoViewBoxSize();
        //    photoViewBox.Child = imageLibrary.LoadedImage;
        //}

        ////
        //// 放缩【 测试 】
        ////
        ////
        //private void ScaleImage(object sender, RoutedEventArgs e)
        //{
        //    imageLibrary.ScaleImage(0.8, 0.8);

        //    RefreshPhotoViewBoxSize();
        //    photoViewBox.Child = imageLibrary.LoadedImage;
        //}

        //
        // 单色
        //
        //
        private void BlackAndWhiteEffectButton_Click(object sender, RoutedEventArgs e)
        {
            imageLibrary.SingleColor(BlackAndWhite.Decoloration);

            MasterImage.Content = imageLibrary.LoadedImage;
        }

        ////
        //// 明暗
        ////
        ////
        //private void IntensityAdjustment(object sender, RoutedEventArgs e)
        //{
        //    ImaginationFactoryDialogs.IntensityAdjustmentDialog win = new ImaginationFactoryDialogs.IntensityAdjustmentDialog(this);

        //    if (win.ShowDialog() == true)
        //    {
        //        imageLibrary.IntensityAdjustment((int)win.intensitySilder.Value);
        //        photoViewBox.Child = imageLibrary.LoadedImage;
        //    }
        //}

        ////
        //// 通道混合器
        ////
        ////
        //private void ChannelMixer(object sender, RoutedEventArgs e)
        //{
        //    imageLibrary.ChannelMixer(ColorPassage.ColorPassage_blue, 50);

        //    photoViewBox.Child = imageLibrary.LoadedImage;
        //}

        ////
        //// 批处理
        ////
        ////
        //private void BatchEffects(object sender, RoutedEventArgs e)
        //{

        //}

        //
        // 加载小绘图程序
        //
        //
        private void SmallPainter_Click(object sender, RoutedEventArgs e)
        {
            //Dialogs.SmallPainter painter = new Dialogs.SmallPainter();
            //painter.Show();
        }


        #endregion


        private void image_ImageFailed(object sender, RoutedEventArgs e)
        {
            this.Close();
        }


    }

}
